﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace JoinBox.WPF.多文档标签.View
{
    //https://www.cnblogs.com/TianFang/p/3969430.html
    public static class HostVisualHost
    {
        /// <summary>
        /// 新建线程让WPF的UI执行
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="container">子控件</param>
        public static void CreateChildInNewThread<T>(ContentControl container) where T : UIElement, new()
        {
            HostVisual hostVisual = new();

            UIElement content = new VisualHost(hostVisual);
            container.Content = content;

            var thread = new Thread(() => {
                var visualTarget = new VisualTarget(hostVisual);

                var control = new T();
                control.Arrange(new Rect(new Point(), content.RenderSize));

                visualTarget.RootVisual = control;
                Dispatcher.Run();
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
        }
    }
    public class VisualHost : FrameworkElement
    {
        Visual child;

        public VisualHost(Visual child)
        {
            if (child == null)
                throw new ArgumentException("child");

            this.child = child;
            AddVisualChild(child);
        }

        protected override Visual GetVisualChild(int index)
        {
            return (index == 0) ? child : null;
        }

        protected override int VisualChildrenCount
        {
            get { return 1; }
        }
    }
}